package com.bishe.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.config.DataException;
import com.bishe.service.FileService;
import com.bishe.mapper.FileMapper;
import com.bishe.pojo.FileInfo;
import com.bishe.util.FileUtils;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * 文件接口实现
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileInfo> implements FileService {

    @Override
    public List<FileInfo> getByDataId(String dataId) {

        return list(new LambdaQueryWrapper<FileInfo>()
                .eq(FileInfo::getDataId, dataId)
        );

    }

    @Override
    public void upload(MultipartFile file, String dataId) {
        if (StrUtil.isEmpty(dataId)) {
            throw new DataException("dataId为空！");
        }

        if (file == null) {
            throw new DataException("文件为空！");
        }

        //如果有文件先删除
        List<FileInfo> byDataId = getByDataId(dataId);
        if (CollUtil.isNotEmpty(byDataId)) {
            byDataId.forEach(s -> {
                deleteFile(dataId);
            });
        }
        String ID = IdUtil.fastSimpleUUID();
        String fileName = FileUtils.uploadFile(file,ID);

        if (StrUtil.isEmpty(fileName)) {
            throw new DataException("格式错误！");
        }
        //上传成功则保存文件记录
        FileInfo fileInfo1 = new FileInfo();
        fileInfo1.setId(ID);
        fileInfo1.setDataId(dataId);
        fileInfo1.setCreateTime(new DateTime());
        fileInfo1.setSuffix(FileUtil.getSuffix(fileName));
        fileInfo1.setName(ID+"."+FileUtil.getSuffix(fileName));
        save(fileInfo1);
    }

    @Override
    public void deleteFile(String fileId) {
        FileInfo fileInfo = getOne(new LambdaQueryWrapper<FileInfo>().eq(FileInfo::getDataId, fileId));
        if (fileInfo == null) {
            throw new DataException("文件不存在！");
        }
        String dirPath = FileUtils.getDirPath();
        //文件的下载路径
        String filePath = dirPath + File.separator + fileInfo.getName();

        File file = new File(filePath);

        FileUtil.del(file);

        this.remove(new LambdaQueryWrapper<FileInfo>().eq(FileInfo::getDataId, fileId));
    }

    @Override
    public FileInfo getByDateId(String id) {
        if (StrUtil.isEmpty(id)) {
            throw new DataException("id为空");
        }

        return getOne(new LambdaQueryWrapper<FileInfo>()
                .eq(FileInfo::getDataId, id), false);
    }

}
